import React, {useCallback, useEffect, useRef, useState} from "react";
import {
    Alert,
    Button, Divider,
    Drawer,
    Form,
    Input,
    InputNumber, message,
    Radio,
    Space,
    Switch,
    Table, Tooltip,
    Typography
} from "antd";
import {
    ImagePullResultProp,
    ImageSearchDrawerProp,
    ImageSearchProp,
    ImageSearchQueryProp
} from "@/pages/docker/modules";
import {ColumnsType} from "antd/es/table";
import {imagesPull, imagesPullResult, imagesSearch} from "@/api/docker";
import {useRequest} from "ahooks";
import {Result} from "ahooks/lib/useRequest/src/types";
import {ImagesTagsTable} from "@/pages/docker/components";

const ImageSearchDrawer: React.FC<ImageSearchDrawerProp> = ({visible, close}) => {

    const columns: ColumnsType<ImageSearchProp> = [
        {
            title: '名称',
            key: 'name',
            dataIndex: 'name',
            align: 'center',
            ellipsis: true,
            width: 120,
            render: (text) => <Typography.Link>{text}</Typography.Link>
        },
        {
            title: '官方',
            key: 'isOfficial',
            dataIndex: 'isOfficial',
            align: 'center',
            width: 80,
            render: (text, record) => <Switch checkedChildren="开启" unCheckedChildren="关闭" defaultChecked={record.isOfficial} />
        },
        {
            title: '自动化',
            key: 'isOfficial',
            dataIndex: 'isOfficial',
            align: 'center',
            width: 80,
            render: (text, record) => <Switch checkedChildren="是" unCheckedChildren="否" defaultChecked={record.isAutomated} />
        },
        {
            title: '点赞数',
            key: 'star',
            dataIndex: 'star',
            width: 80,
            align: 'center'
        },
        {
            title: '描述',
            key: 'desc',
            dataIndex: 'desc',
            align: 'center',
            ellipsis: true,
        },
    ]


    const [btnLoading, setBtnLoading] = useState<boolean>(false);
    const [tag, setTag] = useState<string>('latest');
    const [tagVersion, setTagVersion] = useState<string>('latest');
    const [datasource, setDatasource] = useState<ImageSearchProp[]>([])
    const [query, setQuery] = useState<ImageSearchQueryProp>({isAutomated: -1, isOfficial: -1});
    const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
    const [form] = Form.useForm<ImageSearchQueryProp>();
    const [pullResult, setPullResult] = useState<ImagePullResultProp>({} as ImagePullResultProp)
    const {loading, run} = useRequest(
        imagesSearch, {
            manual: true,
            onSuccess: (data)=> setDatasource(data)
        });

    const imagePull = useRequest(imagesPullResult, {
        manual: true,
        pollingInterval: 2000,
        pollingWhenHidden: false,
        onSuccess: (data) => {
            setPullResult(data);
            if (data.status === 2 || data.status === 0) {
                imagePull.cancel();
                setPullResult({} as ImagePullResultProp);
                setSelectedRowKeys([]);
                setBtnLoading(false);
                setTagVersion('latest')
                setTag('latest')
            }
        }
    })

    const submitForm = () => form.validateFields().then(value => run(value))


    const imagePullHandler = async () => {
        if (selectedRowKeys.length <= 0) {
            message.error('请先选择要拉取的镜像，再点击拉取按钮！');
            return
        }
        const result = await imagesPull(selectedRowKeys[0] + ":" + (tagVersion === 'other' ? tag : tagVersion));
        setPullResult(result);
        message.success("开始拉取镜像......");
        imagePull.run(result.id) // 开始请求数据
        setBtnLoading(true);
    }



    useEffect(() => {
        form.setFieldsValue({...query, isOfficial: -1, isAutomated: -1, limit: 10});
        return () => {
            form.resetFields();
            setDatasource([]);
            setSelectedRowKeys([]);
            imagePull.cancel();
            setTagVersion('latest');
            setTag('latest');
            setPullResult({} as ImagePullResultProp);
        }
    }, [visible])

    return <Drawer
        width={700}
        title="拉取镜像"
        placement="right"
        onClose={() => close(false)}
        open={visible}
        extra={
            <Space>
                <Button type="primary" danger onClick={()=> close(false)}>关闭</Button>
                <Button type="primary" onClick={() => submitForm()} loading={loading}>搜索</Button>
            </Space>
        }
    >
        <Form labelCol={{ span: 3 }}
              wrapperCol={{ span: 21 }}
              form={form}
              layout="horizontal"
              name="form_in_modal"
        >
            <Form.Item name="name" label="镜像名称" rules={[{ required: true, message: '请输入镜像名称' }]}>
                <Input placeholder="请输入镜像名称" />
            </Form.Item>
            <Form.Item name="isOfficial" label="官方镜像">
                <Radio.Group>
                    <Radio value={-1}>全部</Radio>
                    <Radio value={0}>非官方</Radio>
                    <Radio value={1}>官方</Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item name="isAutomated" label="自动化">
                <Radio.Group>
                    <Radio value={-1}>全部</Radio>
                    <Radio value={0}>非自动化</Radio>
                    <Radio value={1}>自动化</Radio>
                </Radio.Group>
            </Form.Item>
            <Form.Item name="limit" label="返回数量">
                <InputNumber style={{width: '100%'}} min={1} placeholder="请输入每次返回镜像数量" />
            </Form.Item>
            <Form.Item name="stars" label="点赞数量">
                <InputNumber style={{width: '100%'}} min={1} placeholder="请输入最少点赞数量" />
            </Form.Item>
        </Form>
        <Divider />
        <Table
            bordered
            size={'small'}
            columns={columns}
            dataSource={datasource}
            style={{ marginTop: 10 }}
            rowKey={(record) => record.name}
            pagination={false}
            rowSelection={{
                type: 'radio',
                selectedRowKeys: selectedRowKeys,
                onChange: (selectedRowKeys: React.Key[]) => {
                    setSelectedRowKeys([...selectedRowKeys.map(item => item as string)])
                }
            }}
        />
        <Divider />
        <Space>
            <div>镜像版本：</div>
            <Radio.Group value={tagVersion} onChange={e => setTagVersion(e.target.value as string)}>
                <Radio value={'latest'}>最新</Radio>
                <Radio value={'other'}>选择</Radio>
            </Radio.Group>
            { tagVersion === 'other' && <Tooltip title="镜像Tag信息无法获取，可以到https://hub.docker.com/search?q=进行查询">
                <Input placeholder="输入镜像指定的版本信息" value={tag} onChange={e => setTag(e.target.value as string)} />
            </Tooltip> }
        </Space>
        <Divider />
        <Space style={{marginTop: 10, textAlign: 'right'}}>
            <Button type='primary' onClick={imagePullHandler} disabled={btnLoading}>拉取</Button>
            {pullResult.status ?
                (pullResult.status === 1 ?
                    <Typography.Text type="warning">正在拉取镜像......</Typography.Text> :
                    (pullResult.status === 0 ?
                        <Typography.Text type="danger">拉取镜像失败</Typography.Text> :
                        <Typography.Text type="success">拉取镜像成功</Typography.Text>)) :
                null}
        </Space>
    </Drawer>

}

export default ImageSearchDrawer;